#!/usr/bin/env python
import os,sys,json
base_dir = os.path.dirname(os.path.dirname(__file__))
sys.path.append(base_dir)
from log.logger import logger


class gman(object):
    g_info_dir = '{}/config/group'.format(base_dir)
    @classmethod
    def help(cls):
        print('''
    gamn.add_group: Create host group
        Param(Separated by spaces):[groupname] [hostname,ip address]
         Eg: gman.add_group webs 10.123.0.1,10.123.0.2
    gman.add_host:  Add host to hostgroup
        Param:[groupname] [hostname,ip]
        Eg: solt.py add_host webs 10.123.0.3
    gman.del_host:  Delet host to hostgroup
        Param:[groupname] [hostname]
        Eg: gman.del_host webs 1.1.1.2,1.1.1.1
    gman.del_group:  Delet host group
        Param:[groupname]
        Eg: gman.del_group webs
    gman.show_group:  View group
        Param:[groupname| *]
        Eg: gman.show_group *
                ''')
    @classmethod
    def get_func(cls):
        return getattr(gman, sys.argv[1][5:])

    @classmethod
    def get_groups(cls):
        with open(cls.g_info_dir, 'r') as f:
            g_info = json.loads(f.read())
        return g_info

    @classmethod
    def write_groups(cls, g_info):
        with open(cls.g_info_dir, 'w') as f:
            f.write(json.dumps(g_info))

    @classmethod
    def add_group(cls, g_name, *args):
        g_info = cls.get_groups()
        if ',' in str(*args):
            host_list = str(*args).split(',')
        else:
            host_list = list(args)
        g_info.update({g_name: host_list})
        cls.write_groups(g_info)
        if g_name == str(*args):
            pass
        else:
            logger.info('Add the host group:{}-Success!'.format(g_name))

    @classmethod
    def add_host(cls, g_name, *args):
        '''
        在分组中添加主机，可批量添加
        :param g_name:
        :param args:
        :return:
        '''
        g_info = cls.get_groups()
        if ',' in str(*args):
            host_list = str(*args).split(',')
        else:
            host_list = args
        try:
            for host in host_list:
                g_info[g_name].append(host)
        except KeyError:
            print("\033[31;1m--No the group!\033[0m")
        else:
            cls.write_groups(g_info)
            logger.info('The host group:{}-add host-Success!'.format(g_name))

    @classmethod
    def del_host(cls, g_name, *args):
        '''
        在分组中添加主机，可批量添加
        :param g_name:
        :param args:
        :return:
        '''
        g_info = cls.get_groups()
        if ',' in str(*args):
            host_list = str(*args).split(',')
        else:
            host_list = args
        try:
            for host in host_list:
                g_info[g_name].remove(host)
        except KeyError:
            print("\033[31;1m--No the group!\033[0m")
        else:
            cls.write_groups(g_info)
            logger.info('The host group:{}-del host-Success!'.format(g_name))

    @classmethod
    def del_group(cls, g_name,args=None):
        g_info = cls.get_groups()
        try:
            del g_info[g_name]
        except KeyError:
            print("\033[31;1m--No the group!\033[0m")
        else:
            cls.write_groups(g_info)
            if args == str(sys.argv[2]):
                pass
            else:
                logger.info('Del the host group:{}-Success!'.format(g_name))
    @classmethod
    def show_group(cls,g_name):
        g_info = cls.get_groups()
        try:
            print('{}:{}' .format(g_name,g_info[g_name]))
        except KeyError:
            print("\033[31;1m--No the group!\033[0m")